﻿using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using 凯蒽斯.Dto;
using 凯蒽斯.ExpansionPge;
using 凯蒽斯.Help;

namespace 凯蒽斯.page
{
    
    /// <summary>
    /// HomeControl1.xaml 的交互逻辑
    /// </summary>
    public partial class HomeControl1 : UserControl
    {
        private readonly DispatcherTimer _timer = new DispatcherTimer();
        public ObservableCollection<AlarmRecord> DataItems { get; set; }
        public HomeControl1()
        {
            InitializeComponent();
            InitializeData(); // 使用同步初始化，确保数据立即加载
            // 配置定时器：间隔1秒（根据需求调整，如500ms）
            _timer.Interval = TimeSpan.FromSeconds(1);
            // 绑定定时器触发事件（循环读取的核心）
            _timer.Tick += async (s, e) => await Timer_TickAsync();
            _timer.Start();
        }

        private async Task Timer_TickAsync()
        {
            if (MainWindow.valuePairs.TryGetValue("plc时间", out object timeValue))
            {
                // 步骤2：安全转换为实际的数组类型（如Int64[]）
                var timeArray = timeValue as Int64[];

                // 步骤3：校验数组有效性
                if (timeArray != null && timeArray.Length >= 6)
                {
                    year.Text = timeArray[0].ToString();
                    moon.Text = timeArray[1].ToString(); // 建议改为month，更符合语义
                    day.Text = timeArray[2].ToString();
                    hours.Text = timeArray[3].ToString();
                    minutes.Text = timeArray[4].ToString();
                    seconds.Text = timeArray[5].ToString();
                }
                
            }
        }

        private void InitializeData()
        {
            DataItems = new ObservableCollection<AlarmRecord>();


            DataContext = this;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            new HistoricalAlerts().Show();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            DataItems.Clear();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            try
            {
                ushort years = (ushort)yearR.Text.ObjToInt();
                ushort momm = (ushort)moonR.Text.ObjToInt();
                ushort days = (ushort)dayR.Text.ObjToInt();
                ushort hour = (ushort)hoursR.Text.ObjToInt();
                ushort minute = (ushort)minutesR.Text.ObjToInt();
                ushort secnd = (ushort)secondsR.Text.ObjToInt();
                var modbusSetting = MainWindow.modbusSettings.Where(x => x.Description == "plc时间").First();

                Task.Run(async () =>
                {
                    // 执行异步写入操作（不依赖UI线程，无需回到UI）
                    await MainWindow.modbusHelp.WriteSingleRegisterAsync(
                        (byte)modbusSetting.unitId,
                        ((ushort)modbusSetting.startAddress),years
                        ).ConfigureAwait(false);

                    await MainWindow.modbusHelp.WriteSingleRegisterAsync(
                        (byte)modbusSetting.unitId,
                        (ushort)(modbusSetting.startAddress + 1),
                        momm).ConfigureAwait(false);

                    await MainWindow.modbusHelp.WriteSingleRegisterAsync(
                        (byte)modbusSetting.unitId,
                        (ushort)(modbusSetting.startAddress + 2),
                        days).ConfigureAwait(false);

                    await MainWindow.modbusHelp.WriteSingleRegisterAsync(
                        (byte)modbusSetting.unitId,
                        (ushort)(modbusSetting.startAddress + 3),
                        hour).ConfigureAwait(false);

                    await MainWindow.modbusHelp.WriteSingleRegisterAsync(
                        (byte)modbusSetting.unitId,
                        (ushort)(modbusSetting.startAddress + 4),
                        minute).ConfigureAwait(false);

                    await MainWindow.modbusHelp.WriteSingleRegisterAsync(
                        (byte)modbusSetting.unitId,
                        (ushort)(modbusSetting.startAddress + 5),
                        secnd).ConfigureAwait(false);

                }).Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
        }
    }
} 
    

